# -*- coding: utf-8 -*-
from typing import List
from tencentcloud.common import credential
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.sms.v20210111 import sms_client, models
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile

from app.conf.config import settings
from app.core.exception.errors import ErrorException
from app.core.logger import api_logger


class TencentSms:
    def __init__(self):
        try:
            cred = credential.Credential(settings.SMS_SECRET_ID, settings.SMS_SECRET_KEY)
            httpProfile = HttpProfile()
            httpProfile.reqMethod = "POST"  # post请求(默认为post请求)
            httpProfile.reqTimeout = 30    # 请求超时时间，单位为秒(默认60秒)
            httpProfile.endpoint = "sms.tencentcloudapi.com"  # 指定接入地域域名(默认就近接入)
            clientProfile = ClientProfile()
            clientProfile.signMethod = "TC3-HMAC-SHA256"  # 指定签名算法
            clientProfile.language = "en-US"
            clientProfile.httpProfile = httpProfile
            client = sms_client.SmsClient(cred, "ap-guangzhou", clientProfile)
            self.client = client
            self.app_id = settings.SMS_APP_ID
            # self.sign_name = settings.SMS_SIGN_NAME
            # self.template_id = settings.SMS_SIGN_NAME
        except TencentCloudSDKException as err:
            api_logger.error(f"TencentSms Error {err}")

    def send_sms(self, mobile, template_param_set: List, sign_name=settings.SMS_SIGN_NAME, template_id=settings.SMS_TEMPLATE_ID):
        try:
            req = models.SendSmsRequest()
            req.SmsSdkAppId = self.app_id
            req.SignName = sign_name
            req.TemplateId = template_id
            req.TemplateParamSet = template_param_set
            req.PhoneNumberSet = [mobile]
            req.SessionContext = ""
            req.ExtendCode = ""
            req.SenderId = ""
            resp = self.client.SendSms(req)
            # 输出json格式的字符串回包
            api_logger.info(f"send_sms:{resp}")
            if resp.SendStatusSet[0].Code != 'Ok':
                raise ErrorException("请不要频繁发送验证码")
        except TencentCloudSDKException as err:
            api_logger.error(f"TencentSms send_sms Error {err}")
            raise ErrorException("验证码发送失败")


